<template>
	<view>
		<cu-custom  :isBack="true">
			<block slot="content">个人信息</block>
		</cu-custom>
	
		<form @submit="userInfoSub">
			<view class="cu-form-group" style="border-top: 1px solid #f8f8f8;">
				<view class="title">昵称</view>
				<input placeholder="请输入昵称" type="nickname" class="text-right" v-model="userInfo.nickName" @blur="validateName" ></input>
				<view v-if="nameErroe" class="validation-error">{{ nameErroe }}</view>
			</view>
			<view class="cu-form-group">
				<view class="title">手机号</view>
				<input placeholder="请输入手机号" class="text-right" v-model="userInfo.phone"
					@click="showPhone =true"></input><text class="cuIcon-right"></text>
			</view>
			<view class="cu-form-group">
				<view class="title">头像</view>
				<view class="text-right">
					<!-- #ifdef MP -->
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" >
						<image class="cu-avatar radius" :src="userInfo.avatarUrl"></image>
					</button>
					<!-- #endif -->
					<!-- #ifndef MP -->
					<view class="cu-avatar radius bg-gray" @tap="chooseImage"
						:style="'background-image:url(' + userInfo.avatarUrl + ')'"></view>
					<!-- #endif -->
				</view>
			</view>
			<view class="cu-form-group">
				<view class="title">性别</view>
				<view>
					<radio-group class="block" @change="sexChange">
						<radio class='red' :class="userInfo.sex=='1'?'checked':''"
							:checked="userInfo.sex=='1'?true:false" value="1" style="transform:scale(0.7)"></radio>男
						<radio class='red margin-left-sm' :class="userInfo.sex=='2'?'checked':''"
							:checked="userInfo.sex=='2'?true:false" value="2" style="transform:scale(0.7)"></radio>女
					</radio-group>
					<view v-if="genderErroe" class="validation-error genderErroe">{{ genderErroe }}</view>
				</view>
			</view>
			<view class="mar">
				<button class="cu-btn shadow-blur block margin-sm round bottom-btn" style="background-color: #18b1bb;color: #fff;width: 500rpx;height: 63rpx;margin: 0 auto;" formType="submit">保存</button>
				<!-- <button class="cu-btn  block margin-sm  bottom-btn line-gray round" @tap="logout">退出登录</button> -->
			</view>
		</form>
		<!-- 修改手机号 -->
		<view class="cu-modal" :class="showPhone==true?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">更换手机号</view>
					<view class="action" @tap="showPhone=false">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view>
					<view class="cu-form-group">
						<view class="title">新手机号</view>
						<input placeholder="请输入手机号" class="text-left" name="phone" v-model="form.phone" @blur="validatePhone"></input>
						<view v-if="phoneError" class="validation-error">{{ phoneError }}</view>
					</view>
					<view class="cu-form-group">
						<view class="title">验证码</view>
						<input placeholder="请输入验证码" class="text-left" name="code" v-model="form.code" @blur="validateUserCode"></input>
						<view  v-if="codeUserError" class="validation-error code-error">{{ codeUserError }}</view>
						<u-toast ref="uToast"></u-toast>
						<!-- <u-verification-code :seconds="seconds" @end="end" @start="start" ref="uCode" @change="codeChange" unique-key="page-a"></u-verification-code>
						<u-button class="codeStyle" style="background-color: rebeccapurple;z-index: 999999;" @tap="getCode">{{tips}}</u-button> -->
						<button class="get-code-con cu-btnsss bg-green shadow" :class="[isActive ? activeCls : '',errorCls]" :disabled="smsbtn.codeShow"
						  @click="getCode">{{smsbtn.codeText}}</button>
					<!-- 	<button class='cu-btn bg-green shadow' @tap="getCode">验证码</button> -->
					</view>
					<view>
						<button class="cu-btn shadow-blur block margin-sm round bottom-btn" style="background-color: #18b1bb;color: #fff;"
							@click="phoneSub">保存</button>
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import validate from '@/utils/validate';
	import config from 'config/env';
	import {
		editObj,
		editPhone
	} from '@/api/userinfo.js';
	import {
		sendSmsCode
	} from '@/api/smscode.js';
	import regMix  from '@/mixins/regular.js'
	export default {
	    mixins: [regMix],
		data() {
			return {
				themeColor:'bgWhite',
				//按钮禁用切换
				isActive: false,
				activeCls: 'active',
				errorCls: 'get-code-con',
				timerID: null,
				// 验证码信息状态
				smsbtn: {
				  codeCount: '',
				  codeShow: false,
				  codeText: '获取验证码',
				  errCode:false
				},
				pageDesign: {
					pageName: '设置'
				},
				tips: '',
				// refCode: null,
				seconds: 60,
				theme: getApp().globalData.theme,
				showPhone: false,
				showSex: false,
				picker: [{
						name: '男',
					},
					{
						name: '女',
					},
				],
				radio: '',
				userInfo: '',
				form: {},
				switchVal: false,
				tips: '',
				imageValue:[]
				
			};
		},
		onShow() {
			this.getUserInfo()
		},
		onLoad(options) {},
		methods: {
			
			codeChange(text) {
				this.tips = text;
			},
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				console.log('123456789')
					if (!this.form.phone) {
						this.phoneError = '请输入手机号';
						return;
					}
					if (!uni.$u.test.mobile(this.form.phone)) {
						 this.phoneError = '请输入正确的手机号';
						return;
					}
					
					uni.showLoading({
						title: '正在获取验证码'
					})
					
					this.numDown()
					
					sendSmsCode(this.form).then(res => {
						uni.showToast({
							title: '验证码已发送',
							icon: 'none',
							duration: 3000
						});
						// 通知验证码组件内部开始倒计时
						// this.$refs.uCode.start();
						// this.form.code = res.data.code
					});
				
				
			},
			
			/**
			 * 性别选择
			 */
			sexChange(e) {
				console.log(e.detail.value)
				this.userInfo.sex = e.detail.value;
			},
			chooseImage() {
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						console.log(tempFilePaths[0]+'-------')
						this.uploadAvatar(tempFilePaths[0]);
					}
				});
			},
			uploadAvatar(filePath) {
				// let rquestUrl = 'http://localhost:9999/mallapi/file/upload'
				
			
				 let rquestUrl = config.basePath +'/mallapi/file/upload';
				
				
				// let rquestUrl = `/mallapi/file/upload`
				
				let _this = this
				uni.uploadFile({
					header: {
						'Tenant-Id':'1590229800633634816',
						'hx-token': uni.getStorageSync('hx-token') ? uni.getStorageSync('hx-token') : null, // 请求token
						'timestamp': new Date().getTime(),
						//#ifdef MP-WEIXIN
						'client-type': 'WX-MA', //客户端微信小程序
						'app-id': uni.getAccountInfoSync().miniProgram.appId, //小程序appId
						//#endif
						//#ifdef APP-PLUS
						'client-type': 'APP', //客户端类型APP
						//#endif
						//#ifdef H5
						'client-type': 'H5', //客户端H5
						//#endif
						//#ifdef MP-ALIPAY
						'client-type': 'ALI-MA', //客户端支付宝小程序
						'app-id': config.aliAppId, //小程序appId
						//#endif
					},
					url: rquestUrl,
					filePath: filePath,
					name: 'file',
					formData: {
						'fileType': 'image'
					},
					success: (uploadFileRes) => {
						let data = JSON.parse(uploadFileRes.data);
						_this.userInfo.avatarUrl = data.data
					}
				});
			},
			/**
			 * 修改个人信息
			 */
			userInfoSub(e) {
				if (!this.userInfo.nickName) {
					this.nameErroe = '请输入姓名'
					return;
				}
				if (!this.userInfo.sex) {
					this.genderErroe = '请选择性别'
					return;
				}
				editObj({
					id: this.userInfo.id,
					sex: this.userInfo.sex,
					nickName: this.userInfo.nickName,
					avatarUrl: this.userInfo.avatarUrl
				}).then(res => {
					uni.navigateBack({
						success: () => {
							let page = getCurrentPages().pop();
							if (page) {
								page.onLoad(page.options); //执行上个页面的方法
							};
						}
					})
					// uni.navigateBack();
				})
			},
			/**
			 * 修改手机号
			 */
			phoneSub() {
				if (!this.form.phone) {
					// uni.$u.toast('请输入手机号');
					 this.phoneError = '请输入手机号';
					return;
				}
				if (!uni.$u.test.mobile(this.form.phone)) {
					 this.phoneError = '请输入正确的手机号';
					// uni.$u.toast('请输入正缺的手机号');
					return;
				}
				if (!this.form.code) {
					// uni.$u.toast('请输入验证码');
					 this.codeUserError = '请输入验证码';
					return;
				}
				editPhone(this.form).then(res => {
					this.userInfo.phone = this.form.phone;
					
					if(res.code === -1){
						this.codeUserError = res.msg
					}else{
						this.getUserInfo()
						this.showPhone = false;
						this.form = {};
					}
					
					
				
				})
			},
			// 获取用户信息
			getUserInfo() {
				let that = this;
				this.$store.dispatch("GetInfo").then((res) => {
					that.userInfo = res
				}).catch(() => {})
			},
			logout() {
				let that = this;
				uni.showModal({
					content: '确认退出系统吗？',
					cancelText: '我再想想',
					success(res) {
						if (res.confirm) {
							// uni.removeStorageSync('hx-token'); // 清除 hx-token
							that.$store.dispatch("Logout").then(() => {
								getApp().globalData.shoppingCartCount = 0;
								uni.reLaunch({
									url: '/pages/home/index'
								});
							})
						}
					}
				});


			},
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				this.uploadAvatar(avatarUrl)
			}
		},
	}
</script>
<style lang="scss" scoped>
	page{
		background-color: #f8f8f8;
	}
	.mar{
		margin-top: 15px;
	}
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}

	.avatar-wrapper {
		padding-left: 0rpx;
		padding-right: 0rpx;
		background-color: #fff;
	}
	
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
	.validation-error {
	  color: red;
	  font-size: 12px;
	}
	.genderErroe{
		margin-left: 20px;
	}
	.code-error{
		margin-right: 10px;
	}
	.bgLiner{
		background: #fff;
		color: #000;
		border-bottom: 1px solid #f8f8f8;
	}
	.cu-form-group{
		border-top: 0.5px solid #f8f8f8 !important;
	}
	.text-left{
		font-size: 26rpx;
		color: #999;
	}
	.cu-btnsss{
		display: flex;
		justify-content: center;
		align-items: center;
		height: 28px !important;
		font-size: 24rpx !important;
		padding: 5px 10px !important;
		letter-spacing: 1rpx !important;
	}
	
	
</style>
